var $express = require('express');
var $result = require('../../common/result');
var $cryptoUtil = require('../../common/crypto_util');
var $mysql = require('./common/mysql');


var router = $express.Router();

var oauth_host = "oauth.anysdk.com";
var oauth_path = "/api/User/LoginOauth/";
var resJson = null;
var checkLogin = function(postData, callback){
    var options={
        host:oauth_host,
        path:oauth_path,
        method:"post",
        headers:{
            "Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",
            "Content-Length":postData.length,
//	     "User-Agent":"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; BOIE9;ZHCN)"
        }
    };

    console.log("#post url:\n"+oauth_host+oauth_path)
    console.log("#post data:\n"+postData)
    var reqToAnysdk=require("http").request(options,function(resFromAnysdk){
        resFromAnysdk.setEncoding("utf8");
        resFromAnysdk.on("data",function(data){

            resJson = JSON.parse(data);
            if (resJson && (resJson.status=="ok")) {


                $mysql.query("select id from tb_user where id = ?",
                    [resJson.data.openid],function (result) {
                        console.log("weixinLogin result",result)
                        if(result.length===0){
                            $mysql.query("insert into tb_user(id) values(?)",resJson.data.openid);
                        }
                });

                resJson.ext = {token:resJson.data.openid};
                callback(JSON.stringify(resJson));
            }else{
                callback(JSON.stringify(resJson));
            }

            console.log("#return data:\n"+JSON.stringify(resJson));
        });

    });

    reqToAnysdk.write(postData);
    reqToAnysdk.end();

}

router.all('/weixin', function(req, res, next) {
    var info ='';
    req.addListener('data', function(chunk){
        console.log("data",chunk);
        info += chunk;
    });
    req.addListener('end', function(){
        console.log("end");
        checkLogin(info, function(msg){
            res.write(msg);
            res.end();
        });
    });

});

/* 登录*/
router.all('/account', function(req, res, next) {

    console.log(req.body,req.params,req.query)

    var params = req.query;

    $mysql.query("select id from tb_user where username=? and password = ?",
        [params.username,$cryptoUtil.md5(params.password)],function (result) {
        res.send($result.success.replaceData({token:result.map(item=>item.id).join()}))
    });

});
//注册
router.get('/register', function(req, res, next) {


    var params = req.query;
    $mysql.query("insert into tb_user (id,username,password,create_time,update_time)values(?,?,?,?,?)",
        [$cryptoUtil.uuid(),params.username,$cryptoUtil.md5(params.password),new Date(),new Date()],function (result) {
            res.send($result.success.replaceData({token:"1"}))
    });
});

module.exports = router;
